package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIDWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {


    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIDWorker redisIDWorker;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 优惠券秒杀
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        /**
         * 1.判断是否在可售时间范围
         * 2.判断库存
         * 更新库存
         * 3.生成订单
         * 4.返回订单id
         *
         */

        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher == null) {
            log.info("优惠券不存在！");
            return Result.fail("优惠券不存在！");
        }
        LocalDateTime beginTime = voucher.getBeginTime();
        LocalDateTime endTime = voucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();

        //判断是否在可售范围
        if(now.isBefore(beginTime) || now.isAfter(endTime)) {
            return Result.fail("未在可售时间范围内！");
        }
        if(voucher.getStock() < 0){
            return Result.fail("库存不足！");
        }


        //创建锁对象        针对一人一单锁
        Long userId = UserHolder.getUser().getId();
        //SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, redisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);

        try {

            //获取锁
            boolean isLock = lock.tryLock();
            //boolean isLock = lock.tryLock(600);
            if(!isLock) {
                return Result.fail("不能重复下单！");
            }
            //获取代理对象
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            //生成订单
            return proxy.createVoucherOrder(voucherId);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        }finally {

            lock.unlock();

        }
        //释放锁


    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId = UserHolder.getUser().getId();
        //查询订单
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();

        //判断是否存在
        if (count > 0) {
            return Result.fail("不能重复下单！");
        }

//测试仓库连接成功


        //更新库存
        //乐观锁
        // （判断线程在操作时是否有其他线程在做更新操作）
        //CAS法 compare and set
        //
        //
        // where stock>0 提升效率
        // set stock = stock-1,voucher_id = voucherId where stock>0


        // 解决超卖
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock-1")
                .eq("voucher_id", voucherId)
                //.eq("stock", voucher.getStock())
                .gt("stock", 0)
                .update();

        if(!success) {
            return Result.fail("库存不足！");
        }

        //下单
        // 生成订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIDWorker.nextID("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        //返回订单id
        return Result.ok(orderId);
    }
}
